// Copyright © 2024 Kube logging authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package output

import (
	"github.com/cisco-open/operator-tools/pkg/secret"

	"github.com/kube-logging/logging-operator/pkg/sdk/logging/model/types"
)

// +name:"VMware LogInsight"
// +weight:"200"
type _hugoVMwareLogInsight interface{} //nolint:deadcode,unused

// +docName:"VMware LogInsight output plugin for Fluentd"
/*
For details, see [https://github.com/vmware/fluent-plugin-vmware-loginsight](https://github.com/vmware/fluent-plugin-vmware-loginsight).

## Example output configurations

```yaml
spec:
  vmwareLogInsight:
    scheme: https
    ssl_verify: true
    host: MY_LOGINSIGHT_HOST
    port: 9543
    agent_id: XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
    log_text_keys:
	- log
	- msg
	- message
    http_conn_debug: false
```
*/
type _docVMwareLogInsight interface{} //nolint:deadcode,unused

// +name:"VMware LogInsight"
// +url:"https://github.com/vmware/fluent-plugin-vmware-loginsight/releases/tag/v1.4.2"
// +version:"1.4.2"
// +description:"Store logs in VMware LogInsight"
// +status:"GA"
type _metaVMwareLogInsight interface{} //nolint:deadcode,unused

// +kubebuilder:object:generate=true
// +docName:"VMwareLogInsight"
// Send your logs to VNMware LogInsight
type VMwareLogInsightOutput struct {
	// agent_id generated by your LI (default: 0)
	AgentID string `json:"agent_id,omitempty"`

	// +kubebuilder:validation:Enum:=nil;basic

	// Type of authentication to use (nil,basic) (default: nil)
	Authentication *string `json:"authentication,omitempty"`

	// +docLink:"Buffer,../buffer/"
	Buffer *Buffer `json:"buffer,omitempty"`

	// +docLink:"Secret,../secret/"
	CAFile *secret.Secret `json:"ca_file,omitempty"`

	// Rename fields names (default: {"source" => "log_source"})
	ConfigParam map[string]string `json:"config_param,omitempty"`

	// Flatten hashes to create one key/val pair w/o losing log data (default: true)
	FlattenHashes *bool `json:"flatten_hashes,omitempty"`

	// Separator to use for joining flattened keys (default: _)
	FlattenHashesSeparator string `json:"flatten_hashes_separator,omitempty"`

	// If set, enables debug logs for http connection (default: false)
	HTTPConnectionDebug bool `json:"http_conn_debug,omitempty"`

	// +kubebuilder:validation:Enum:=post

	// HTTP method (post) (default: post)
	HTTPMethod string `json:"http_method,omitempty"`

	// VMware Aria Operations For Logs Host ex. localhost
	Host string `json:"host,omitempty"`

	// Keys from log event whose values should be added as log message/text to
	// VMware Aria Operations For Logs. These key/value pairs won't be
	// expanded/flattened and won't be added as metadata/fields.
	//
	// (default: ["log", "message", "msg"])
	LogTextKeys []string `json:"log_text_keys,omitempty"`

	// Number of bytes per post request (default: 4000000)
	MaxBatchSize int `json:"max_batch_size,omitempty"`

	// +docLink:"Secret,../secret/"
	Password *secret.Secret `json:"password,omitempty"`

	// VMware Aria Operations For Logs ingestion api path ex. 'api/v1/events/ingest'
	// (default: api/v1/events/ingest)
	Path string `json:"path,omitempty"`

	// VMware Aria Operations For Logs port ex. 9000 (default: 80)
	Port int `json:"port,omitempty"`

	// Raise errors that were rescued during HTTP requests? (default: false)
	RaiseOnError bool `json:"raise_on_error,omitempty"`

	// Simple rate limiting: ignore any records within `rate_limit_msec` since the
	// last one (default: 0)
	RateLimitMilliseconds int `json:"rate_limit_msec,omitempty"`

	// Number of retries (default: 3)
	RequestRetries int `json:"request_retries,omitempty"`

	// http connection ttl for each request (default: 5)
	RequestTimeout int `json:"request_timeout,omitempty"`

	// SSL verification flag (default: true)
	SSLVerify *bool `json:"ssl_verify,omitempty"`

	// +kubebuilder:validation:Enum:=http;https

	// HTTP scheme (http,https) (default: http)
	Scheme string `json:"scheme,omitempty"`

	// +kubebuilder:validation:Enum:=json

	// Serialization (json) (default: json)
	Serializer string `json:"serializer,omitempty"`

	// Keys from log event to rewrite for instance from 'kubernetes_namespace' to
	// 'k8s_namespace' tags will be rewritten with substring substitution and
	// applied in the order present in the hash (Hashes enumerate their values in
	// the order that the corresponding keys were inserted see:
	// https://ruby-doc.org/core-2.2.2/Hash.html
	//
	// (default {
	//   'kubernetes_':'k8s_',
	//   'namespace':'ns',
	//   'labels_':'',
	//   '_name':'',
	//   '_hash':'',
	//   'container_':''
	// })
	ShortenKeys map[string]string `json:"shorten_keys,omitempty"`

	// +docLink:"Secret,../secret/"
	Username *secret.Secret `json:"username,omitempty"`
}

func (in *VMwareLogInsightOutput) ToDirective(secretLoader secret.SecretLoader, id string) (types.Directive, error) {
	vmwLi := types.OutputPlugin{
		PluginMeta: types.PluginMeta{
			Type:      "vmware_loginsight",
			Id:        id,
			Directive: "match",
			Tag:       "**",
		},
	}

	if in.Buffer != nil {
		bufDirective, err := in.Buffer.ToDirective(secretLoader, id)
		if err != nil {
			return nil, err
		}

		vmwLi.SubDirectives = append(vmwLi.SubDirectives, bufDirective)
	}

	params, err := types.NewStructToStringMapper(secretLoader).StringsMap(in)
	if err != nil {
		return nil, err
	}

	vmwLi.Params = params

	return &vmwLi, nil
}
